import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'
var camera
var scene
var renderer
var mouse
let w = window.innerWidth,h=window.innerHeight
let LEN = 2000
function main(){
  creatCamera()
  createGrid()
  createLight()
  createRenderer()
  createGeometry()
  createGltf()
}

function creatCamera(){
  scene = new THREE.Scene()

  camera = new THREE.PerspectiveCamera(45,w/h,1,10000)
  camera.position.x = 200
  camera.position.y = 300
  camera.position.z = 500
  camera.up.y = 1
  camera.lookAt(scene.position)

}
function createRenderer(){
  renderer = new THREE.WebGLRenderer()
  renderer.setSize(w,h)
  // renderer.setClearColor(0xffffff)
  // renderer.setClearColor('#8edee2')
  document.body.appendChild(renderer.domElement)
  
}
var mesh
function createGeometry(){
  var geometry = new THREE.BoxGeometry(50,50,50)
  var colors = []
  for (let i = 0; i < geometry.attributes.position.array.length; i+=12) {
    let r = Math.random()
    let g = Math.random()
    let b = Math.random()
    colors.push(
      r,g,b,
      r,g,b,
      r,g,b,
      r,g,b,
    )
  }
  geometry.setAttribute('color',new THREE.BufferAttribute(new Float32Array(colors), 3))
  var material = new THREE.MeshBasicMaterial({
    vertexColors: THREE.VertexColors,
  });
  mesh = new THREE.Mesh(geometry,material)
  var axis1 = new THREE.AxesHelper(100)
  axis1.add(mesh)
  scene.add(mesh)
  scene.add(axis1)
}
var objMesh
var groupMesh
var axis
function createGltf(){
  let lanse = new THREE.TextureLoader().load('/static/lanse.jpeg')
  new OBJLoader().load('/static/male.obj',(obj)=>{
    console.log('geometry',obj);
    obj.traverse((child)=>{
      if(child.isMesh){
        child.material.map = lanse
      }
    })
    obj.position.set(-100,-25,100)
    objMesh = obj
    scene.add(objMesh)

    axis = new THREE.AxesHelper(200)
    axis.position.set(-100,-25,100)
    axis.add(objMesh)
    scene.add(axis)

    var group = new THREE.Group()
    group.add(obj)
    group.add(axis)
    
    groupMesh = group
    scene.add(group)
  })
}
function createLight(){

  var light = new THREE.DirectionalLight(0xffff00, 0.7, 1000, 1)
  light.position.set(200, 500, 800)
  scene.add(light)

}
function createGrid(){
  var grid = new THREE.GridHelper(1000,20)
  scene.add(grid)
}
function render() {
  mesh.rotateY(0.01)

  axis&&(axis.rotateY(0.05))
  objMesh&&(objMesh.rotateY(0.05))

  groupMesh&&(groupMesh.rotateY(0.01))
  renderer.render(scene, camera)
  requestAnimationFrame(render)
}

main()
render()

// /** --------------------鼠标控件对象--------------------- */
let controls = new OrbitControls(camera, renderer.domElement); //创建控件对象
controls.addEventListener("change", render); //监听鼠标、键盘事件
